package com.hx.eaz.controllers

import com.hx.eaz.domains.*
import com.hx.eaz.models.AnalyzeQuery
import com.hx.eaz.models.CompanyInfo
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import java.math.BigDecimal

@Controller
@RequestMapping(value = ["data"])
@CrossOrigin()
class DataController {

    private val logger = LoggerFactory.getLogger(DataController::class.java)

    private val cache = hashMapOf<String, List<CompanyInfo>>()

    @ResponseBody
    @RequestMapping(value = ["analyze"])
    fun analyze(@RequestBody query: AnalyzeQuery): ResponseEntity<AnalyzeResult> {
        return ResponseEntity.ok(
                Analyzer(query, cache).analyze()
        )
    }

    @ResponseBody
    @RequestMapping(value = ["upload"])
    fun uploadDataFile(file: MultipartFile): Any {
        saveDataFile(file)
        return ResponseEntity.ok(cache.keys)
    }

    private fun saveDataFile(file: MultipartFile) {
        val ins = file.inputStream
        val workBook = XSSFWorkbook(ins)
        val parser = Parser()
        val list = parser.companyInfoParse(workBook)
        cache[file.originalFilename?.split(".")?.get(0) ?: "temp"] = list
    }

    @ResponseBody
    @RequestMapping(value = ["cates"])
    fun findAllCategory(): Any {
        if (cache.isEmpty()) {
            return ResponseEntity.ok(setOf<Any>())
        }
        val set = cache
                .flatMap { e -> e.value }
                .flatMap { c -> c.cateList }
                .filterNot { it.isBlank() }
                .toSet()
        return ResponseEntity.ok(set)
    }

    @ResponseBody
    @RequestMapping(value = ["countries"])
    fun findAllCountry(): Any {
        if (cache.isEmpty()) {
            return ResponseEntity.ok(setOf<Any>())
        }
        val set = cache.flatMap { e -> e.value }.map { c -> c.country }.toSet()
        return ResponseEntity.ok(set)
    }

    @ResponseBody
    @RequestMapping(value = ["cached"])
    fun findAllCached(): Any {
        return ResponseEntity.ok(cache.keys)
    }
}